import { ref } from 'vue'
import {
  getRankings,
  getSongsListInfo
} from '@/service/find-music/ranking-list'

import LocalCache from '@/utils/cache'

export function InitDatas() {
  const topList: any = ref([])
  const allTopList = ref([])
  const allSongsList: any = ref([])
  const endLength = 6
  const currentIndex = ref(0)

  //获取排行榜详情数据
  function getTopList(): void {
    getRankings().then((res: any) => {
      allTopList.value = res.list
      topList.value = res.list.splice(0, endLength)
      InitSongsList()
    })
  }
  // 初始化数据
  const InitSongsList = () => {
    topList.value.map((item: any) => {
      const obj = { ...item }
      obj.children = []
      allSongsList.value.push(obj)
    })
    fullSongsliost()
  }

  // 填充对应歌曲数据到children
  const fullSongsliost = () => {
    allSongsList.value.map((item: any, index: number) => {
      getIdSongs(topList.value[index].id, item.children)
    })
  }

  // 根据id查找对应排行榜歌曲
  function getIdSongs(id: number, data: any) {
    getSongsListInfo(id).then((res: any) => {
      const songs = res.playlist.tracks.splice(0, 8)
      data.push(...songs)
      currentIndex.value++
      if (currentIndex.value == endLength) {
        // 最后一次请求成功
        // ps：不能采用使用循环最后一次来验证数据是否全部请求过来，因为可能中间的数据请求比最后一次慢
        currentIndex.value = 0
        LocalCache.setCache('allSongsList', JSON.stringify(allSongsList.value))
        LocalCache.setCache('allTopList', JSON.stringify(allTopList.value))
        LocalCache.setCache('SongsTime', new Date().getTime())
      }
    })
  }

  return { getTopList, allSongsList, allTopList }
}
